package com.minivision.fdiot.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public final class IPUtils {
  
  /**
   * 根据主机名获取服务器地址
   *
   * @return Ip地址
   */
  public static String getServerIp(String hostname) {
    try {
      return InetAddress.getByName(hostname).getHostAddress();
    } catch (UnknownHostException e) {
      log.error(e.getMessage(), e);
    }
    return null;
  }
  

  /**
   * 获取当前主机服务器地址
   *
   * @return Ip地址
   */
  public static String getServerIp() {
    // 获取操作系统类型
    String sysType = System.getProperties().getProperty("os.name");
    if (sysType.toLowerCase().startsWith("win")) {  // 如果是Windows系统，获取本地IP地址
      try {
        return InetAddress.getLocalHost().getHostAddress();
      } catch (UnknownHostException e) {
        log.error(e.getMessage(), e);
      }
      return null;
    } 
    
    return getIpByEthNum("eth0"); // 兼容Linux
  }

  /**
   * 根据网络接口获取IP地址
   * @param ethNum 网络接口名，Linux下是eth0
   * @return
   */
  private static String getIpByEthNum(String ethNum) {
    try {
      Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
      InetAddress ip;
      while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = allNetInterfaces.nextElement();
        if (ethNum.equals(netInterface.getName())) {
          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
          while (addresses.hasMoreElements()) {
            ip = addresses.nextElement();
            if (ip != null && !ip.isLinkLocalAddress() && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
              return ip.getHostAddress();
            }
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return null;
  }

  /**
   * 获取公网IP
   * @return
   */
  public static String getInternetIP() {
    URL url;
    try {
      url = new URL("http://ip.chinaz.com/getip.aspx");
    } catch (MalformedURLException e) {
      log.error(e.getMessage(), e);
      return null;
    }

    try(InputStream ins = url.openConnection().getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(ins));
        ) {
      StringBuilder webContent = new StringBuilder();
      String str = null;
      while ((str = bReader.readLine()) != null) {
        webContent.append(str);
      }
      String json = webContent.toString();
      return json.substring(json.indexOf("'") + 1, json.indexOf(",") - 1);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return null;
  }

  public static void main(String[] args) throws Exception {
    //用 getLocalHost() 方法创建的InetAddress的对象
    InetAddress address = InetAddress.getLocalHost();
    System.out.println(address.getHostAddress());//获取IP地址
    System.out.println(getServerIp());
    System.out.println(getInternetIP());
  }

}
